<script setup>
import { computed, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import {delayApi} from "@/apis/task.js"
//延迟提货表单数据
const formData = ref({
	delayReason: '', // 延迟原因
	delayTime: '', //  延迟时间
	id: '' //  任务 id
});

//原定提货时间
const planTime = ref('');

onLoad((options) => {
	console.log(options.planDepartureTime);
	formData.value.id = options.id;
	planTime.value = options.planDepartureTime;
});

//延迟时间的代码
const onPickerChange = (e) => {
	const date = planTime.value.split(' ')[0]; //传什么以什么分开
	formData.value.delayTime = `${date} ${e.detail.value}`;
};

//统计用户输入延迟原因字数
const total = computed(() => {
	return formData.value.delayReason.length
});

/**
		 * 校验思路：
			  1. 使用计算属性计算选择的当天提货时间和原定时间是否超过两小时：end - start > 0 && end - start <= 7200 * 1000
			  2. 使用计算属性计算字数是否在 50 字范围内： wordsCount.value <= 50 && wordsCount.value > 0
			  3. 校验不通过，使用error类名标红提醒
		 */
//延迟时间的校验

const totalOk = computed(() => {
	return  total.value<=50&& total.value>=0
});

const isDelayTimeOk = computed(() => {
	const start=+new Date(planTime.value)
	//获取选择延迟时间的时间戳
	const end=+new Date(formData.value.delayTime)
	return end-start>0&&end - start <= 7200 * 1000
});


//兜底校验
  // 是否允许提交表单  按钮的禁用已经实现了兜底校验
  const isSubmitDisable = computed(() => {
    return !isDelayTimeOk.value || !totalOk.value
  })


//点击按钮
 const btn=async()=>{
	await delayApi(formData.value)
	setTimeout(()=>{
		uni.showToast({
			title:'延迟成功'
		},1000)
	})
	uni.reLaunch({
		url:'/pages/task/index'
	})
 }
</script>

<template>
	<view class="page-container">
		<uni-list :border="false">
			<!-- showArrow右侧小箭头 -->
			<uni-list-item title="原定时间 " showArrow :rightText="planTime" />
			<uni-list-item title="延迟时间" showArrow>
				<template v-slot:footer>
					<!-- 通过插槽显示时间选择器。内置组件picker，mode=time用来时间选择 -->
					<!-- @change获取改变事件  :value显示时间-->
					<picker class="time-picker" mode="time" @change="onPickerChange" :value="planTime.split('')[1]">
						<text v-if="formData.delayTime === ''">不可超过2个小时</text>
						<text v-else :class="{ error: !isDelayTimeOk }">{{ formData.delayTime }}:00</text>
					</picker>
				</template>
			</uni-list-item>
			<uni-list-item direction="column">
				<template v-slot:body>
					<view class="textarea-wrapper" >
						<textarea class="textarea" placeholder-style="color: #818181" placeholder="请输入延迟提货原因" v-model="formData.delayReason"></textarea>
						<text class="words-count" :class="{ error: !totalOk }">{{ total }}/50</text>
					</view>
				</template>
			</uni-list-item>
			<uni-list-item :border="false">
				<template v-slot:body>
					<button @click="btn" :disabled="!isSubmitDisable" class="button" >提交</button>
				</template>
			</uni-list-item>
		</uni-list>
	</view>
</template>

<style lang="scss" scoped>
@import './index.scss';
</style>
